Python用asyncio来建立异步的web服务器
import asyncio
async def handle_http_request(reader, writer):
# 读取 HTTP 请求
data = await reader.read(1024)
message = data.decode()
# 简单解析请求路径
lines = message.splitlines()
request_line = lines[0] if lines else ""
parts = request_line.split()
if len(parts) >= 2:
path = parts[1]
else:
path = "/"
# 构造 HTTP 响应
response_body = f"Hello! You requested path: {path}"
response_headers = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
f"Content-Length: {len(response_body)}\r\n"
"Connection: close\r\n"
"\r\n"
)
response = response_headers + response_body
# 发送响应
writer.write(response.encode())
await writer.drain()
# 关闭连接
writer.close()
async def main():
server = await asyncio.start_server(
handle_http_request, '127.0.0.1', 8080
)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())